from typing import List

from fastapi import APIRouter, Body

import controller.business
import schemas
from components.router import CenterRoute
from controller.business import bulk_insert_businesses_with_checking, update_one_business_with_checking, delete_business
from ioservice.business import list_all_business_types
from models.business import Business
from loguru import logger

router = APIRouter(route_class=CenterRoute)


@router.get("/business_type")
async def list_business_types():
    return await list_all_business_types()


@router.post("/business")
async def create_one_business(business: Business):
    insert_ids = await bulk_insert_businesses_with_checking([business])
    return {"id": str(insert_ids[0])}


@router.put("/business/{business_id}")
async def alter_business(business_id: str, business: Business):
    business.fields_check(exclude=["ocode", "ocode_num", "create_time"])
    modified_num = await update_one_business_with_checking(business_id, business)
    logger.debug(f"update customer [{business_id}], modified num {modified_num}")
    return {"modified_num": modified_num}


@router.delete("/business/bulk")
async def bulk_delete_business(business_ids: List[str] = Body(None, embed=True)):
    deleted_num = await delete_business(business_ids)
    return {"deleted_num": deleted_num}


@router.post("/business/search", response_model=schemas.SearchResult, response_model_exclude_none=True)
async def search_business_by_conditions(param: schemas.SearchParam):
    result = await controller.business.search_business_by_params(param)
    return result
